<?php

/**
 * LayoutHelper helps create page view.
 *
 * PHP versions 5
 * CAKEPHP versions 2.x
 * 
 * Green CMS - Content Management System and Framework Powerfull by Cakephp
 * Copyright 2012, GREEN GLOBAL CO., LTD (toancauxanh.vn)
 * 
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Technology Lab No.I <tech1@toancauxanh.vn>
 * @link          
 * @package       Green.Helper
 * @since         Green v 1.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
class LayoutHelper extends AppHelper {

    /**
     * List language cached
     * 
     * @var array
     */
    protected $_listLanguages = null;

    /**
     * Current URL of requested
     * 
     * @var array
     */
    protected $_here = null;

    /**
     * Before layout callback.
     *
     * Parse Layout Block.
     *
     * @param string $layoutFile The layout about to be rendered.
     * @return void
     */
    function beforeLayout($layoutFile) {

        if ($this->_View->theme && $this->_View->layout
                && Configure::read('Themes.' . $this->_View->theme . '.layout.' . $this->_View->layout)) {

            $Model = ClassRegistry::init('Block.Block');

            $regions = $Model->Region->find('list', array(
                'recursive' => -1,
                'conditions' => array(
                    'not' => array(
                        'region' => -1,
                    ),
                    'theme' => $this->_View->theme . '.' . $this->_View->layout
                ),
                'fields' => array('block_id', 'region')));
            if (empty($regions)) {
                return;
            }
            $language = Router::language();

            // @Todo sử dụng bindModel HasMany và unbindModel HABTM 
            $blocks = $Model->find('all', array(
                'order' => 'Block.weight',
                'conditions' => array(
                    'Block.id' => array_keys($regions),
                    'or' => array(
                        array('Block.language' => null),
                        array('Block.language' => ''),
                        'Block.language LIKE' => '%s:' . strlen($language) . ':"' . $language . '"%',
                        'Block.language' => 'a:0:{}'
                    )
                ),
                'fields' => array(
                    'Block.id',
                    'Block.title',
                    'Block.module',
                    'Block.delta',
                    'Block.custom',
                    'Block.content',
                    'Block.params',
                    'Block.include',
                    'Block.exclude'
                ), 'contain' => array('Role' => array('id'))));

            $options = array();

            $roles = Green::getRoles();

            $blockUrl = '';
            if (Router::getParam('admin')) {
                $blockUrl = $this->_View->Html->link(__d('green', 'Configure block'), array(
                    'admin' => true, 'plugin' => 'block', 'controller' => 'block', 'action' => 'edit', '---id---'), array('target' => '_blank'));
                $this->_View->Html->css(array('contextual'), null, array('inline' => false));
                $this->_View->Html->script(array('contextual'), array('inline' => false));
            }

            foreach ($blocks as $block) {
                if (!isset($regions[$block['Block']['id']])) {
                    continue;
                }

                if (!empty($block['Role'])) {

                    $allowed = false;
                    foreach ($block['Role'] as $role) {
                        if (in_array($role['id'], $roles)) {
                            $allowed = true;
                            break;
                        }
                    }
                    if ($allowed === false) {
                        continue;
                    }
                }

                $block = $block['Block'];
                if ($block['include'] && !Router::match($block['include'], $this->request)) {
                    continue;
                }
                if ($block['exclude'] && Router::match($block['exclude'], $this->request)) {
                    continue;
                }

                if ($blockUrl) {
                    $block['links'] = array(str_replace('---id---', $block['id'], $blockUrl));
                }
                $params = (array) $block['params'];
                unset($block['params'], $block['include'], $block['exclude'], $block['Role']);

                $title = $block['title'];

                $this->getEventManager()->dispatch(new CakeEvent('Helper.Layout.beforeBlock', $this, array(&$block, &$params, &$options)));

                if (empty($block['custom'])) {
                    $event = new CakeEvent('Helper.Layout.' . $block['module'] . '.block', $this, array(&$block, &$params, &$options));
                    $this->getEventManager()->dispatch($event);
                    if ($event->isStopped()) {
                        continue;
                    }
                }

                $this->getEventManager()->dispatch(new CakeEvent('Helper.Layout.afterBlock', $this, array(&$block, &$params)));

                if ($title === '<non>') {
                    unset($block['title']);
                }

                $region = $regions[$block['id']];
                switch ($region) {
                    case 'css':
                    case 'title':
                    case 'meta': {
                            break;
                        }
                    default : {
                            $output = $this->_View->element('block', compact('block'));
                        }
                }
                $this->_View->append($region, $output);
            }
            

            //------------------------- Thêm vào dây ----------------------
             if (($dx = Configure::read('App.meta'))) {
                 $Meta = ClassRegistry::init('Meta');
                 if (($data = $Meta->getData($dx['alias'], $dx['id']))) {
                     if (!empty($data['Meta']['title'])) {
                         $this->_View->assign('title', $data['Meta']['title']);
                     }
                    unset($data['Meta']['title']);
                      foreach ($data['Meta'] as $key => $content) {
                        if ($content) {
                             $this->_View->Html->meta($key, $content, array(
                                'block' => 'meta'
                             ));
                          }
                      }
                  }
              }

            
        }
    }

    /**
     * Allows you to override the current domain for a single message lookup.
     *
     * @param string $domain Domain
     * @param string $msg String to translate
     * @param mixed $args Array with arguments or multiple arguments in function
     * @return translated string
     */
    public function t($domain, $message) {
        $this->getEventManager()->dispatch(new CakeEvent('Helper.Layout.t', $this, array(&$domain, &$message)));
        return __d($domain, $message);
    }

    /**
     * Used to output messages in the view.
     *
     * @param string $message Message to be flashed
     * @param array $params Parameters to be sent to layout as view variables
     * @param string $element Element to wrap flash message in.
     * @return string
     */
    public function flash($message, $params = array(), $element = 'flash') {
        $this->getEventManager()->dispatch(new CakeEvent('Helper.Layout.flash', $this, array(&$message, &$params, &$element)));
        $maps = array(
            'error' => __d('green', 'Error'),
            'info' => __d('green', 'Information'),
            'warning' => __d('green', 'Warning'),
            'success' => __d('green', 'Success')
        );
        if (!is_array($params)) {
            $params = array('type' => $params);
        }
        $params['message'] = $message;
        if (empty($params['type']) || !array_key_exists($params['type'], $maps)) {
            $params['type'] = 'error';
        }
        $params = array_merge(array('title' => $maps[$params['type']]), $params);
        return $this->_View->element($element, $params);
    }

    /**
     * Used to output messages in the view.
     *
     * @param string $key
     * @param string $value
     * @param string $reset reset cache.
     * @return string
     */
    public function listLanguages($key = 'code', $value = 'name', $reset = false) {
        $cache = $key . $value;
        if ($reset === true || !isset($this->_listLanguages[$cache])) {
            $this->_listLanguages[$cache] = array();
            foreach (Configure::read('Languages') as $lang) {
                $this->_listLanguages[$cache][$lang[$key]] = $lang[$value];
            }
        }
        return $this->_listLanguages[$cache];
    }

    /**
     * Used to format form output.
     *
     * @param array $layout
     * @param array $fieldset
     * @param array $format.
     * @return string output
     */
    public function form($layout, $fieldset, $format = array()) {
        $this->getEventManager()->dispatch(new CakeEvent('Helper.Layout.form', $this, array(&$layout, &$fieldset, &$format)));
        $default = array(
            'fieldset' =>'<div class="widget-content nopadding">%s</div>',
            'legend' => '<div class="widget-title"><span class="icon"><i class="icon-align-justify"></i></span><h5>%s</h5></div>',
            'rowset' => '%s',
            'double' => '%s',
            'single' => '%s'
        );
        $format = array_merge($default, $format);
        $output = '';
        foreach ($layout as $group) {
            $_output = '';
            list($legend, $rows) = $group;
            foreach ($rows as $row) {
                $row = (array) $row;
                $col1 = (array) $row[0];
                $col2 = count($row) > 1 ? (array) $row[1] : array();
                $_format = '';
                switch (true) {
                    case (empty($col2)): {
                            if (count($col1) === 1) {
                                $_format .= $format['double'];
                            } else {
                                $_format .= str_repeat($format['single'], 2);
                            }
                            break;
                        }
                    default : {
                            foreach (array($col1, $col2) as $_col) {
                                if (count($_col) === 1) {
                                    $_format .= $format['single'];
                                } else {
                                    $_format .= sprintf($format['single'], str_repeat($format['single'], 2));
                                }
                            }
                        }
                }
                $_input = array();
                foreach (array_merge($col1, $col2) as $field) {
                    if (!isset($fieldset[$field])) {
                        trigger_error(__d('debug', 'Fieldset of field %s is missing or duplicate layout config for it.', $field));
                    }
                    $_input[] = $fieldset[$field];
                    unset($fieldset[$field]);
                }
                $_output .= sprintf($format['rowset'], vsprintf($_format, $_input));
            }

            if ($legend) {
                $legend = sprintf($format['legend'], __d('system', $legend));
            }
            $output.= sprintf($format['fieldset'], $legend . $_output);
        }
        if (!empty($fieldset)) {
            trigger_error(__d('debug', 'Layout config of fields %s is missing.', implode(',', array_keys($fieldset))));
        }
        return $output;
    }
    /**
     * Used to format form output.
     *
     * @param array $layout
     * @param array $fieldset
     * @param array $format.
     * @return string output
     */

   public function seoForm($layout, $fieldset, $format) {
         $Meta = ClassRegistry::init('Meta');
        if (($Model = $this->_View->Form->getModel()) && $Model->Behaviors->attached('Meta')) {
             $layout[] = array('SEO OPTIONS', array(
                     array('meta_title', 'meta_keywords'),
                     'meta_description'));
            $this->_View->request->data = array_merge($this->_View->request->data, $Meta->getData($Model->alias, $Model->id));
             $fieldset['meta_title'] = $this->_View->Form->input('Meta.title', array('label' => array('class' => 'control-label'), 'between' => '<div class="controls">','div' => array('class' => 'control-group'),'type' => 'text', 'maxlength' => 128));
            $fieldset['meta_keywords'] = $this->_View->Form->input('Meta.keywords', array('label' => array('class' => 'control-label'), 'between' => '<div class="controls">','div' => array('class' => 'control-group'), 'type' => 'text', 'maxlength' => 128));
           $fieldset['meta_description'] = $this->_View->Form->input('Meta.description', array('label' => array('class' => 'control-label'), 'between' => '<div class="controls">','div' => array('class' => 'control-group'), 'type' => 'textarea', 'maxlength' => 255));
         }
     }


    /**
     * Returns a list of events this object is implementing, when the class is registered
     * in an event manager, each individual method will be associated to the respective event.
     *
     * @return array associative array or event key names pointing to the function
     * that should be called in the object when the respective event is fired
     */



}
